use shq_common::prelude::get_my_pool;
use sqlx::Row;



pub async fn del_dept_approvers(
    ny: u32,
    wfid: u32,
    emid: u32,
    dpid: u32,
) -> anyhow::Result<()> {
    let pool = get_my_pool();
    let mut tr = pool.begin().await?;
    let sql = "delete from hr_dept_approvers where ny = ? and wfid = ? and emid = ? and dpid = ?";
    sqlx::query(sql)
        .bind(ny)
        .bind(wfid)
        .bind(emid)
        .bind(dpid)
        .execute(&mut *tr)
        .await?;
    tr.commit().await?;
    Ok(())
}

pub async fn get_dept_approvers(ny: u32, wfid: u32) -> Result<Vec<u32>, sqlx::Error> {
    let pool = get_my_pool();
    let mut tr = pool.begin().await?;
    let sql = "SELECT dpid from hr_dept_approvers where ny = ? and wfid = ?";
    let rows = sqlx::query(sql)
        .bind(ny)
        .bind(wfid)
        .fetch_all(&mut *tr)
        .await?;
    let mut result = Vec::new();
    for row in rows { 
        let dpid: u32 = row.get("dpid"); 
        result.push(dpid);
    }
    tr.commit().await?;
    Ok(result)
}

pub async fn get_id_dept(ny: u32, ids: Vec<u32>)-> Result<Vec<u32>, sqlx::Error> {
    let pool = get_my_pool();
    let mut tr = pool.begin().await?;
    let sql = "SELECT dpid from hr_dept_approvers where ny = ? and id = ? ";
    let mut result = Vec::new();
    for id in ids {
        let rows = sqlx::query(sql)
            .bind(ny)
            .bind(id)
            .fetch_all(&mut *tr)
            .await?;
        for row in rows { 
            let dpid: u32 = row.get("dpid"); 
            result.push(dpid);
        }
    }
    tr.commit().await?;
    Ok(result)
}